package com.forlove.app.common.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.util.Log;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * 网络连接工具类
 */
public class NetworkUtils {

    public static final String NETWORK_TYPE_UNKNOWN = "UNKNOWN";

    public static final String NETWORK_TYPE_WIFI = "wifi";

    public static final String NETWORK_TYPE_4G = "4G";

    public static final String NETWORK_TYPE_3G = "3G";

    public static final String NETWORK_TYPE_2G = "2G";

    private ConnectivityManager mConnManager;

    private TelephonyManager mPhonyManager;

    private static NetworkUtils sInstance;

    private NetworkUtils(Context context) {
        mConnManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        mPhonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
    }

    public static NetworkUtils instance(Context context) {
        if (sInstance == null) {
            sInstance = new NetworkUtils(context);
        }
        return sInstance;
    }

    /**
     * 获取网络类型（2G、3G和WIFI）
     *
     * @return
     */
    public String getNetworkType() {
        if (isWifiAvailable()) {
            return NETWORK_TYPE_WIFI;
        }

        if (isMobileNetAvailable()) {
            if (isConnection3G()) {
                return NETWORK_TYPE_3G;
            }

            if (isConnection2G()) {
                return NETWORK_TYPE_2G;
            }
            if (isConnection4G()) {
                return NETWORK_TYPE_4G;
            }
        }

        return NETWORK_TYPE_UNKNOWN;
    }

    /**
     * 是否3G网络
     *
     * @return
     */
    public boolean isConnection3G() {
        boolean result = false;
        switch (mPhonyManager.getNetworkType()) {
            case TelephonyManager.NETWORK_TYPE_UMTS: // 3G WCDMA 联通3G Universal
                // Mobile Telecommunication
                // System 完整的3G移动通信技术标准
            case TelephonyManager.NETWORK_TYPE_EVDO_0: // 3G (EVDO 全程 CDMA2000
                // 1xEV-DO) Evolution - Data
                // Only (Data Optimized)
                // 153.6kps - 2.4mbps 属于3G
            case TelephonyManager.NETWORK_TYPE_EVDO_A: // 3G 1.8mbps - 3.1mbps
                // 属于3G过渡，3.5G
            case TelephonyManager.NETWORK_TYPE_HSDPA: // 3.5G 高速下行分组接入 3.5G WCDMA
                // High Speed Downlink
                // Packet Access 14.4mbps
            case TelephonyManager.NETWORK_TYPE_HSUPA: // 3.5G High Speed Uplink
                // Packet Access 高速上行链路分组接入
                // 1.4 - 5.8 mbps
            case TelephonyManager.NETWORK_TYPE_HSPA: // 3G (分HSDPA,HSUPA) High Speed
                // Packet Access
            case TelephonyManager.NETWORK_TYPE_EVDO_B: // 3G EV-DO Rev.B 14.7Mbps 下行
                // 3.5G
            case TelephonyManager.NETWORK_TYPE_HSPAP: // 3G HSPAP 比 HSDPA 快些
            case TelephonyManager.NETWORK_TYPE_EHRPD: // 3G CDMA2000向LTE 4G的中间产物
                // Evolved High Rate Packet
                // Data HRPD的升级
            case 17: // TelephonyManager.NETWORK_TYPE_TD_SCDMA:

                result = true;
                break;
            default:
                break;
        }
        return result;
    }

    /**
     * 是否2G网络
     *
     * @return
     */
    public boolean isConnection2G() {
        boolean result = false;
        switch (mPhonyManager.getNetworkType()) {
            case TelephonyManager.NETWORK_TYPE_UNKNOWN:
            case TelephonyManager.NETWORK_TYPE_GPRS: // 2G(2.5) General Packet Radia
                // Service 114kbps
            case TelephonyManager.NETWORK_TYPE_EDGE: // 2G(2.75G) Enhanced Data Rate
                // for GSM Evolution 384kbps
            case TelephonyManager.NETWORK_TYPE_CDMA: // 2G 电信 Code Division Multiple
                // Access 码分多址
            case TelephonyManager.NETWORK_TYPE_1xRTT: // 2G CDMA2000 1xRTT (RTT -
                // 无线电传输技术) 144kbps 2G的过渡,
            case TelephonyManager.NETWORK_TYPE_IDEN: // 2G Integrated Dispatch
                // Enhanced Networks
                // 集成数字增强型网络
                result = true;
                break;
            default:
                break;
        }
        return result;
    }

    public boolean isConnection4G() {
        switch (mPhonyManager.getNetworkType()) {
            case TelephonyManager.NETWORK_TYPE_LTE:
            case 18:// TelephonyManager.NETWORK_TYPE_IWLAN:
                return true;
        }
        return false;
    }

    /**
     * 检测网络状态是否联通
     *
     * @param context
     * @return
     */
    public boolean isNetworkAvailable() {
        NetworkInfo info = mConnManager.getActiveNetworkInfo();
        return isLinkable(info);
    }

    /**
     * 移动数据网络是否可用
     *
     * @return
     */
    public boolean isMobileNetAvailable() {
        NetworkInfo info = mConnManager
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        return isLinkable(info);
    }

    /**
     * WIFI连接是否可用
     *
     * @return
     */
    public boolean isWifiAvailable() {
        NetworkInfo info = mConnManager
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return isLinkable(info);
    }

    /**
     * 指定类型的连接是否可用
     *
     * @param info
     * @return
     */
    private boolean isLinkable(NetworkInfo info) {
        if ((info != null) && info.isConnected() && info.isAvailable()) {
            return true;
        }
        return false;
    }

    /**
     * 获取wifi地址。
     *
     * @param context 上下文
     * @return mac地址
     */
    public static String getWifiMacAddress(Context context) {
        String wifiMac = "";
        // 加入try catch 解决线上崩溃
        try {
            if (null != context) {
                WifiManager wm = (WifiManager) context
                        .getSystemService(Context.WIFI_SERVICE);
                if (null != wm && null != wm.getConnectionInfo()) {
                    wifiMac = wm.getConnectionInfo().getMacAddress();
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return wifiMac;
    }

    // 获取本地IP
    public static String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e("WifiPreference IpAddress", ex.toString());
        }

        return null;
    }

}
